package com.lfz.quality_effect.service.impl;

import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lfz.quality_effect.constant.LfzConstant;
import com.lfz.quality_effect.mapper.TCollectionBalanceCopyMapper;
import com.lfz.quality_effect.model.dto.CivilSettledRateDTO;
import com.lfz.quality_effect.model.dto.TotalSettledRateDTO;
import com.lfz.quality_effect.model.entity.TCollectionBalance;
import com.lfz.quality_effect.model.entity.TCollectionBalanceCopy;
import com.lfz.quality_effect.model.vo.EleScoreRankVO;
import com.lfz.quality_effect.model.vo.ScoreRankVO;
import com.lfz.quality_effect.service.TCollectionBalanceCopyService;
import com.lfz.quality_effect.utils.ExcelListener;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class TCollectionBalanceCopyServiceImpl extends ServiceImpl<TCollectionBalanceCopyMapper, TCollectionBalanceCopy> implements TCollectionBalanceCopyService {


    @Override
    public void uploadTotalSettledRate(MultipartFile file, String dataTime) {

        ExcelListener listener = new ExcelListener();
        InputStream inputStream;
        try {
            inputStream = file.getInputStream();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        //传入参数
        ExcelReader excelReader = new ExcelReader(inputStream, ExcelTypeEnum.XLS,null, listener);
        Sheet sheet = new Sheet(1, 1, TotalSettledRateDTO.class);

        //读取信息
        excelReader.read(sheet);
        List<Object> objectList =listener.getDatas();

        ArrayList<TCollectionBalanceCopy> tList = new ArrayList<>();
        for (int i = 0; i < objectList.size(); i++) {
            TotalSettledRateDTO totalSettledRateDTO = (TotalSettledRateDTO) objectList.get(i);
            BigDecimal totalSettledRate = totalSettledRateDTO.getTotalSettledRate().setScale(4,BigDecimal.ROUND_UP);
            TCollectionBalanceCopy tCollectionBalanceCopy = new TCollectionBalanceCopy();
            if (!totalSettledRateDTO.getCourt().equals("0.0")){
                tCollectionBalanceCopy.setCourt(totalSettledRateDTO.getCourt());
                tCollectionBalanceCopy.setTotalSettledRate(totalSettledRate);
                tCollectionBalanceCopy.setDataTime(dataTime);
                tCollectionBalanceCopy.setCreateTime(LocalDateTime.now());
                tList.add(tCollectionBalanceCopy);
            }

        }


        QueryWrapper<TCollectionBalanceCopy> wrapper = new QueryWrapper<>();
        wrapper.eq("data_time",dataTime);
        Integer count = this.getBaseMapper().selectCount(wrapper);
        if (count != null && count > 0){
            // 更新
            log.info("已存在{}的数据",dataTime);
            for (TCollectionBalanceCopy tCollectionBalanceCopy : tList) {
                Map<String, Object> paramMap = new HashMap<>();
                paramMap.put("court",tCollectionBalanceCopy.getCourt());
                paramMap.put("totalSettledRate",tCollectionBalanceCopy.getTotalSettledRate());
                paramMap.put("dataTime",dataTime);


                this.getBaseMapper().updateTotalRate(paramMap);
            }
        }
        // 插入
        else {
            this.saveBatch(tList);
        }

    }

    @Override
    public void uploadCivilSettledRate(MultipartFile file, String dataTime) {
        ExcelListener listener = new ExcelListener();
        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        //传入参数
        ExcelReader excelReader = new ExcelReader(inputStream, ExcelTypeEnum.XLS,null, listener);
        Sheet sheet = new Sheet(1, 1, CivilSettledRateDTO.class);

        //读取信息
        excelReader.read(sheet);
        List<Object> objectList =listener.getDatas();


        ArrayList<TCollectionBalanceCopy> tList = new ArrayList<>();
        for (int i = 0; i < objectList.size(); i++) {
            CivilSettledRateDTO civilSettledRateDTO = (CivilSettledRateDTO) objectList.get(i);
            // 保留四位小数
            BigDecimal civilSettledRatio = civilSettledRateDTO.getCivilSettledRate().setScale(4, BigDecimal.ROUND_UP);
            Integer civilUnsettled  = civilSettledRateDTO.getCivilOld() + civilSettledRateDTO.getCivilNew() - civilSettledRateDTO.getCivilSettled();
            TCollectionBalanceCopy tCollectionBalanceCopy = new TCollectionBalanceCopy();

            if (civilSettledRateDTO.getCourt().equals("0.0")){
                tCollectionBalanceCopy.setCourt("合计");
            }else {
                tCollectionBalanceCopy.setCourt(civilSettledRateDTO.getCourt());
            }

            tCollectionBalanceCopy.setCivilSettled(civilSettledRateDTO.getCivilSettled());
            tCollectionBalanceCopy.setCivilUnsettled(civilUnsettled);
            tCollectionBalanceCopy.setCivilSettledRate(civilSettledRatio);
            tCollectionBalanceCopy.setCreateTime(LocalDateTime.now());
            tCollectionBalanceCopy.setDataTime(dataTime);

            tList.add(tCollectionBalanceCopy);

        }

        QueryWrapper<TCollectionBalanceCopy> wrapper = new QueryWrapper<>();
        wrapper.eq("data_time",dataTime);
        Integer count = this.getBaseMapper().selectCount(wrapper);

        wrapper.eq("court","合计");
        TCollectionBalanceCopy tCollectionBalanceCopy1 = this.getOne(wrapper);

        if (count != null && count > 0){
            // 更新
            log.info("已存在{}的数据",dataTime);
            for (TCollectionBalanceCopy tCollectionBalanceCopy : tList) {
                Map<String, Object> paramMap = new HashMap<>();
                paramMap.put("court",tCollectionBalanceCopy.getCourt());
                paramMap.put("civilSettled",tCollectionBalanceCopy.getCivilSettled());
                paramMap.put("civilUnsettled",tCollectionBalanceCopy.getCivilUnsettled());
                paramMap.put("civilSettledRate",tCollectionBalanceCopy.getCivilSettledRate());
                paramMap.put("dataTime",dataTime);

                // 总结案率先插入 修改民商事结案率的同时也要插入  合计的数据
                if (tCollectionBalanceCopy.getCourt().equals("合计") && Objects.isNull(tCollectionBalanceCopy1)){
                    this.getBaseMapper().insert(tCollectionBalanceCopy);
                }

                this.getBaseMapper().updateCivilRate(paramMap);
            }

        }
        // 插入
        else {
            this.saveBatch(tList);
        }
    }



    /**
     * 获取民商事结案率排名
     * @return
     */
    @Override
    public List<ScoreRankVO> getCivilSettledRateRank() {

        String maxTime = this.getBaseMapper().getMaxTime();
        //获取最大时间的收结存
        List<TCollectionBalanceCopy> tCollectionBalanceCopyList =   this.list(new LambdaQueryWrapper<TCollectionBalanceCopy>()
                .eq(TCollectionBalanceCopy::getDataTime,maxTime)
                .orderByDesc(TCollectionBalanceCopy::getCivilSettledRate));
        if (CollectionUtils.isEmpty(tCollectionBalanceCopyList)){
            return null;
        }
        tCollectionBalanceCopyList =   tCollectionBalanceCopyList.stream().filter(item-> (!item.getCourt().contains("高级") && !item.getCourt().contains("中级") && !item.getCourt().equals("合计"))).collect(Collectors.toList());
        List<String> list = new ArrayList<>();
        list.add("乐平市人民法院");
        list.add("景德镇市昌江区人民法院");
        list.add("浮梁县人民法院");
        list.add("景德镇市珠山区人民法院");

        List<ScoreRankVO> scoreRankVOList = new ArrayList<>();

        for (int i=0;i<tCollectionBalanceCopyList.size();i++){
            TCollectionBalanceCopy tCollectionBalanceCopy = tCollectionBalanceCopyList.get(i);

            String court = tCollectionBalanceCopy.getCourt();
            if (list.contains(court)){
                ScoreRankVO scoreRankVO = new ScoreRankVO();
                scoreRankVO.setScore(tCollectionBalanceCopy.getCivilSettledRate());
                scoreRankVO.setCourt(tCollectionBalanceCopy.getCourt());
                scoreRankVO.setSort(i+1);
                scoreRankVOList.add(scoreRankVO);
            }
        }
        TCollectionBalanceCopy tCollectionBalanceCopy =  tCollectionBalanceCopyList.get(0);
        ScoreRankVO scoreRankVO = new ScoreRankVO();
        scoreRankVO.setCourt(tCollectionBalanceCopy.getCourt());
        scoreRankVO.setScore(tCollectionBalanceCopy.getCivilSettledRate());
        scoreRankVO.setSort(1);
        scoreRankVOList.add(scoreRankVO);
        return scoreRankVOList;
    }

    /**
     * 获取民商事结案率趋势图
     * @param startTime
     * @param endTime
     * @return
     */
    @Override
    public  Map<String,List<EleScoreRankVO>> getCivilSettledRateRankTrend(String startTime, String endTime) {
        Map<String,Object> paramMap = new HashMap<>();
        paramMap.put("startTime",startTime);
        paramMap.put("endTime",endTime);

        List<EleScoreRankVO> eleList = new ArrayList<>();
        //标杆法院
        List<EleScoreRankVO> standartCourtList = this.getBaseMapper().getStandardCourt(paramMap);
        Map<String, List<EleScoreRankVO>> eMap =  standartCourtList.stream().sorted(Comparator.comparing(EleScoreRankVO::getScore).reversed()).collect(Collectors.groupingBy(item->item.getDataTime()));
        for (Map.Entry<String,List<EleScoreRankVO>> entry: eMap.entrySet()){
            eleList.add(entry.getValue().get(0));
        }

        List<EleScoreRankVO> eleScoreRankVOList = this.getBaseMapper().getCivilTrend(paramMap);
        Map<String, List<EleScoreRankVO>> groupMap =  eleScoreRankVOList.stream().sorted(Comparator.comparing(EleScoreRankVO::getScore)).collect(Collectors.groupingBy(item->item.getCourt()));
        Map<String,List<EleScoreRankVO>> map = new HashMap<>();

        for (Map.Entry<String,List<EleScoreRankVO>> entry:groupMap.entrySet()){
            String key = entry.getKey();
            if (key.contains(LfzConstant.CHANGJIANG_COURT) || key.contains(LfzConstant.ZHUSHAN_COURT)
                    || key.contains(LfzConstant.FULIANG_COURT) || key.contains(LfzConstant.LEPU_COURT)){
                map.put(entry.getKey(),entry.getValue());
            }
        }
        map.put("标杆法院",eleList);
        return map;
    }


    /**
     * 获取总结案率排名
     * @return
     */
    @Override
    public List<ScoreRankVO> getTotalSettledRateRank() {
        String maxTime = this.getBaseMapper().getMaxTime();
        //获取最大时间的收结存
        List<TCollectionBalanceCopy> tCollectionBalanceCopyList =   this.list(new LambdaQueryWrapper<TCollectionBalanceCopy>()
                .eq(TCollectionBalanceCopy::getDataTime,maxTime)
                .orderByDesc(TCollectionBalanceCopy::getTotalSettledRate));
        if (CollectionUtils.isEmpty(tCollectionBalanceCopyList)){
            return null;
        }
        tCollectionBalanceCopyList =   tCollectionBalanceCopyList.stream().filter(item-> (!item.getCourt().contains("高级") && !item.getCourt().contains("中级") && !item.getCourt().equals("合计"))).collect(Collectors.toList());
        List<String> list = new ArrayList<>();
        list.add("乐平市人民法院");
        list.add("景德镇市昌江区人民法院");
        list.add("浮梁县人民法院");
        list.add("景德镇市珠山区人民法院");

        List<ScoreRankVO> scoreRankVOList = new ArrayList<>();

        for (int i=0;i<tCollectionBalanceCopyList.size();i++){
            TCollectionBalanceCopy tCollectionBalanceCopy = tCollectionBalanceCopyList.get(i);

            String court = tCollectionBalanceCopy.getCourt();
            if (list.contains(court)){
                ScoreRankVO scoreRankVO = new ScoreRankVO();
                scoreRankVO.setScore(tCollectionBalanceCopy.getTotalSettledRate());
                scoreRankVO.setCourt(tCollectionBalanceCopy.getCourt());
                scoreRankVO.setSort(i+1);
                scoreRankVOList.add(scoreRankVO);
            }
        }
        TCollectionBalanceCopy tCollectionBalanceCopy =  tCollectionBalanceCopyList.get(0);
        ScoreRankVO scoreRankVO = new ScoreRankVO();
        scoreRankVO.setCourt(tCollectionBalanceCopy.getCourt());
        scoreRankVO.setScore(tCollectionBalanceCopy.getTotalSettledRate());
        scoreRankVO.setSort(1);
        scoreRankVOList.add(scoreRankVO);
        return scoreRankVOList;
    }

    /**
     * 获取总结案率趋势图
     * @param startTime
     * @param endTime
     * @return
     */
    @Override
    public Map<String, List<EleScoreRankVO>> getTotalSettledRateRankTrend(String startTime, String endTime) {
        Map<String,Object> paramMap = new HashMap<>();
        paramMap.put("startTime",startTime);
        paramMap.put("endTime",endTime);

        List<EleScoreRankVO> eleList = new ArrayList<>();
        //标杆法院
        List<EleScoreRankVO> standartCourtList = this.getBaseMapper().getTotalStandardCourt(paramMap);
        Map<String, List<EleScoreRankVO>> eMap =  standartCourtList.stream().sorted(Comparator.comparing(EleScoreRankVO::getScore).reversed()).collect(Collectors.groupingBy(item->item.getDataTime()));
        for (Map.Entry<String,List<EleScoreRankVO>> entry: eMap.entrySet()){
            eleList.add(entry.getValue().get(0));
        }

        List<EleScoreRankVO> eleScoreRankVOList = this.getBaseMapper().getTotalTrend(paramMap);
        Map<String, List<EleScoreRankVO>> groupMap =  eleScoreRankVOList.stream().sorted(Comparator.comparing(EleScoreRankVO::getScore)).collect(Collectors.groupingBy(item->item.getCourt()));
        Map<String,List<EleScoreRankVO>> map = new HashMap<>();

        for (Map.Entry<String,List<EleScoreRankVO>> entry:groupMap.entrySet()){
            String key = entry.getKey();
            if (key.contains(LfzConstant.CHANGJIANG_COURT) || key.contains(LfzConstant.ZHUSHAN_COURT)
                    || key.contains(LfzConstant.FULIANG_COURT) || key.contains(LfzConstant.LEPU_COURT)){
                map.put(entry.getKey(),entry.getValue());
            }
        }
        map.put("标杆法院",eleList);
        return map;
    }
}
